package com.pp.demo.module.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pp.demo.module.user.converter.UserConverter;
import com.pp.demo.module.user.dto.UserDTO;
import com.pp.demo.module.user.entity.User;
import com.pp.demo.module.user.mapper.UserMapper;
import com.pp.demo.module.user.param.UserCreateParam;
import com.pp.demo.module.user.param.UserUpdateParam;
import com.pp.demo.module.user.service.UserRoleService;
import com.pp.demo.module.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pzh
 * @since 2025-07-03 16:01:20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleService userRoleService;

    @Override
    public List<UserDTO> listUser(){
        List<User> userList = this.list();
        return UserConverter.INSTANCE.toDTOList(userList);
    }

    @Override
    public UserDTO getUser(String name){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(User::getName, name);
        User user = this.getOne(queryWrapper);
        UserDTO dto = UserConverter.INSTANCE.toDTO(user);

        // 填充关联数据
        if (dto != null) {
            List<String> roleNames = userRoleService.getRoleNamesByUserId(dto.getId());
            dto.setRoleNames(roleNames);
        }

        return dto;
    }

    @Transactional
    @Override
    public Long createUser(UserCreateParam param){
        User user = UserConverter.INSTANCE.toEntity(param);
        this.save(user);
        // 处理关联关系
        userRoleService.saveUserRoles(user.getId(), param.getRoleIds());
        return user.getId();
    }

    @Override
    public boolean updateUser(Long id, UserUpdateParam param){
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, id)
                .set(User::getName, param.getName())
                .set(User::getAge, param.getAge())
                .set(User::getSex, param.getSex());
        return this.update(updateWrapper);
    }

    @Override
    public boolean removeUser(Long id){
        return this.removeById(id);
    }
}
